package com.lunker.moneyrecord;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class ImportDatabaseTask extends AsyncTask<Void, Void, Boolean>{

	private Context context = null;
	private BetterProgressDialog progressDlg = null;
	private String backup_name = null; 

	public ImportDatabaseTask (Context c, String fname) {
		context = c;
		backup_name = fname;
	}
	
	@Override
	protected void onPreExecute() {
		progressDlg = new BetterProgressDialog(context);
		progressDlg.show();
	}
	
	@Override
	protected Boolean doInBackground(Void... params) {
		
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return false;
		}
		
		SQLiteDatabase dbbak = null;
		
		try {
			//Try to open it for checking whether the file is a sqlite database.
			dbbak = SQLiteDatabase.openDatabase(
					Environment.getExternalStorageDirectory() + "/" + backup_name,
					null,
					SQLiteDatabase.OPEN_READONLY);
			dbbak.close();
		} catch (SQLiteException sqle) {
			//Failing to open database dues to bad database file format.
			return false;
		}
		
		//Copy the backup from SD card to system.
		File fbak = new File(Environment.getExternalStorageDirectory(), backup_name);
		File fsys = new File(Environment.getDataDirectory(), 
				"data/" + context.getPackageName() + "/databases/account_book");
		FileChannel fcin = null;
		FileChannel fcout = null;
		
		try {
			fsys.createNewFile();
			fcin = new FileInputStream(fbak).getChannel();
			fcout = new FileOutputStream(fsys).getChannel();
			fcin.transferTo(0, fcin.size(), fcout);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (fcin != null) {
					fcin.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if (fcout != null) {
					fcout.close();
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		progressDlg.dismiss();
		
		if (result) {
			Toast.makeText(context, context.getString(R.string.import_db_successfully), 
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(context, context.getString(R.string.fail_to_import_db), 
					Toast.LENGTH_SHORT).show();
		}
	}
}
